package com.google.code.swingonfire.showcase.utils;

import java.awt.event.ActionListener;
import java.util.EventListener;

import javax.swing.JComboBox;

public class ComboBoxParameterDefinition extends AbstractParameterDefinition<JComboBox, Object>
{

    public static class Option
    {
        private final String name;
        private final Object value;

        public Option(String name, Object value)
        {
            super();

            this.name = name;
            this.value = value;
        }

        public String getName()
        {
            return name;
        }

        public Object getValue()
        {
            return value;
        }

        @Override
        public String toString()
        {
            return name;
        }

    }

    private final String defaultName;
    private final Option[] options;

    public ComboBoxParameterDefinition(String name, String defaultName, Option... options)
    {
        super(name, Object.class);

        this.defaultName = defaultName;
        this.options = options;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public JComboBox createComponent(EventListener eventListener)
    {
        JComboBox comboBox = new JComboBox(options);

        comboBox.setSelectedItem(getOptionByName(defaultName));
        comboBox.addActionListener((ActionListener) eventListener);
        
        return comboBox;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object getValue(JComboBox component)
    {
        return ((Option) component.getSelectedItem()).getValue();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setValue(JComboBox component, Object value)
    {
        component.setSelectedItem(getOptionByValue(value));
    }

    private Option getOptionByName(String name)
    {
        for (Option option : options)
        {
            if (option.getName().equals(name))
            {
                return option;
            }
        }

        return null;
    }

    private Option getOptionByValue(Object value)
    {
        for (Option option : options)
        {
            if (option.getValue().equals(value))
            {
                return option;
            }
        }

        return null;
    }

}
